﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

using LowLevelGraphics;
using LowLevelGraphics.Filter;

namespace ImageRecognition2.Action
{
    /// <summary>
    /// This will create an average gray image out of pictures from a directory
    /// </summary>
    public class ActionCreateAverageGrayImage : AbstractCommand
    {
        protected bool m_bIncreaseContrast = true;

        /// <summary>
        /// Initializes a new instance of the <see cref="ActionCreateAverageGrayImage"/> class.
        /// </summary>
        /// <param name="_bIncreaseContrast">if set to <c>true</c> [_b increase contrast].</param>
        public ActionCreateAverageGrayImage(bool _bIncreaseContrast)
        {
            m_bIncreaseContrast = _bIncreaseContrast;
        }

        internal ActionCreateAverageGrayImage(ActionCreateAverageGrayImage _ActionCreateAverageGrayImage)
        {
            m_bIncreaseContrast = _ActionCreateAverageGrayImage.m_bIncreaseContrast;
        }

        /// <summary>
        /// Runs the specified sender.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public override void Run(object sender, EventArgs e)
        {
            string sPattern = "*.*";
            string sFolder = string.Empty;

            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() != DialogResult.OK) return;

            sFolder = fd.SelectedPath;

            string[] aDir = Directory.GetFiles(sFolder, sPattern);
            
            List<UnsafeBitmap> aBitmap = new List<UnsafeBitmap>();

            foreach (string sFile in aDir)
            {
                aBitmap.Add(UnsafeBitmap.FromFile(sFile));
            }

            if (m_bIncreaseContrast)
            {
                foreach (UnsafeBitmap bitmap in aBitmap)
                {
                    new ContrastStretch().Execute(bitmap);
                }
            }

            UnsafeBitmap bitmapTemp = BitmapFunctions.CreateAverageBitmap(aBitmap);
            bitmapTemp.Dispose();

            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmapTemp.InternalBitmap;
        }

        public override object Clone()
        {
            return new ActionCreateAverageGrayImage(this);
        }
    }
}
